package com.pmcc.platform.salesman.service;

import com.pmcc.platform.giftGoods.entity.Goods;
import com.pmcc.platform.giftGoods.repository.GoodsRepository;
import com.pmcc.platform.giftGoods.service.GoodsService;
import com.pmcc.platform.salesman.entity.Salesman;
import com.pmcc.platform.salesman.repository.SalesmanRepository;
import com.pmcc.platform.shop.entity.ShopInfo;
import com.pmcc.platform.shop.repository.ShopInfoRepository;
import com.pmcc.platform.shop.vo.ShopDetailVo;
import com.pmcc.platform.shop.vo.ShopDetailsVo;
import com.pmcc.platform.shopping.entity.Shopping;
import com.pmcc.platform.shopping.entity.ShoppingApply;
import com.pmcc.platform.shopping.entity.ShopLibory;
import com.pmcc.platform.shopping.entity.ShoppingGiftChangeLog;
import com.pmcc.platform.shopping.enums.GiftChange;
import com.pmcc.platform.shopping.repository.*;
import com.pmcc.platform.shopping.vo.ApplyLogVo;
import com.pmcc.platform.user.entity.MinShoppingUserInfo;
import com.pmcc.platform.user.enums.MinUserType;
import com.pmcc.platform.user.repository.MinShoppingUserInfoRepository;
import com.pmcc.platform.user.repository.UserInfoRepository;
import com.pmcc.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: basePlatform
 * @description:
 * @author: Mr.Xue
 * @create: 2020-04-25 17:20
 **/
@Slf4j
@Service
@Transactional
public class SalesmanService {

    @Autowired
    SalesmanRepository salesmanRepository;

    @Autowired
    UserInfoRepository userInfoRepository;

    @Autowired
    ShopInfoRepository shopInfoRepository;

    @Autowired
    GoodsGiftRepository goodsGiftRepository;

    @Autowired
    ShoppingRepository shoppingRepository;

    @Autowired
    ShopLiboryRepository shoppingLiboryRepository;

    @Autowired
    GoodsService goodsService;

    @Autowired
    ShoppingApplyRepository shoppingApplyRepository;

    @Autowired
    MinShoppingUserInfoRepository minUserInfoRepository;

    @Autowired
    ShoppingGiftChangeLogRepository shoppingGiftChangeLogRepository;

    @Autowired
    GoodsRepository goodsRepository;

    @Value("${wechatPay.spbillCreateIp}")
    private String spbillCreateIp;

    @Value("${baseConfig.basePath}")
    private String basePath;//公共配置文件路径

    @Value("${qiNiu.bucket}")
    private String bucket;//公共配置文件路径



    /**
     * 查询所有业务员
     *
     * @param antPage
     * @return
     */
    public ApiResultBean queryAllSalesman(AntPage antPage,String name,String phone) {
        ApiResultBean apiResultBean = new ApiResultBean();

        Page<Salesman> salesmanPage = salesmanRepository.findAllByDelFlagAndNameContainsAndPhoneContains("0",name,phone,antPage.getPageRequest());
        if(salesmanPage.getSize()>0){
            for (Salesman salesman: salesmanPage) {
                int a=goodsGiftRepository.countSalesmanNum(salesman.getId(),"1","0");
                salesman.setGetNum(a);
                salesman.setOrganizationName("后台定的固定值");
            }
        }
        apiResultBean.setData(salesmanPage,antPage);
        apiResultBean.setMsg("查询成功！");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    /**
     * 添加分销员
     *
     * @param salesman
     * @return
     */
    public ApiResultBean addSalesman(Salesman salesman) {
        ApiResultBean apiResultBean = new ApiResultBean();

        salesmanRepository.saveAndFlush(salesman);

        apiResultBean.setData(salesman);
        apiResultBean.setMsg("保存成功！");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    /**
     * 删除业务员
     *
     * @param salesmanId
     * @return
     */
    public ApiResultBean deleteSalesman(String salesmanId) {
        ApiResultBean apiResultBean = new ApiResultBean();

        if(StringUtils.isEmpty(salesmanId)){
            apiResultBean.setMsg("删除失败参数为空！");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        Salesman salesman = salesmanRepository.findOne(salesmanId);
        salesman.setDelFlag("1");
        salesmanRepository.saveAndFlush(salesman);

        apiResultBean.setMsg("删除成功！");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }



    /**
     * 修改业务员信息
     *
     * @param salesman
     * @return
     */
    public ApiResultBean modifySalesman(Salesman salesman) {
        ApiResultBean apiResultBean = new ApiResultBean();

        if(StringUtils.isEmpty(salesman.getId())){
            apiResultBean.setMsg("删除失败参数为空！");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }

        Salesman model = salesmanRepository.findOne(salesman.getId());

        model.setPhone(salesman.getPhone());
        model.setName(salesman.getName());
        model.setStatus(salesman.getStatus());

        salesmanRepository.saveAndFlush(model);

        apiResultBean.setMsg("修改成功！");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean lookShop(String salesmanId,AntPage antPage){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(salesmanId)){
            apiResultBean.setMsg("业务员id不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }
        Page<ShopInfo> shopInfos=shopInfoRepository.findAllBySalesmanIdAndDelFlag(salesmanId,"0",antPage.getPageRequest());
        for (ShopInfo shopInfo:shopInfos) {
            Salesman salesman=salesmanRepository.findOne(shopInfo.getSalesmanId());
            shopInfo.setSalesmanName(salesman.getName());
            shopInfo.setSalesmanPhone(salesman.getPhone());

            //查出发送放赠品数量
            int getNum=goodsGiftRepository.countShopNum(shopInfo.getId(),"1","0");
            shopInfo.setGetNum(getNum);
            //查出该店下的现有的导购
            List<Shopping> shoppings=shoppingRepository.findAllByShopIdAndDelFlag(shopInfo.getId(),"0");
            int residueNum=0;
            if(shoppings.size()>0){
                for (Shopping shopping:shoppings ) {
                    //查出导购当前手上的赠品余量
                    List<ShopLibory> list=shoppingLiboryRepository.findAllByShopIdAndDelFlag(shopping.getShopId(),"0");
                    if(list.size()>0){
                        for (ShopLibory shoppingLibory: list) {
                            int s=shoppingLibory.getGoodsNum();
                            residueNum=residueNum+s;
                        }


                    }

                }
            }
            shopInfo.setResidueNum(residueNum);


        }
        apiResultBean.setData(shopInfos,antPage);
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("查询成功");
        return  apiResultBean;
    }

    public ApiResultBean lookShopping(String salesmanId,AntPage antPage){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(salesmanId)){
            apiResultBean.setMsg("业务员id不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }
        Page<ShopInfo> shopInfos=shopInfoRepository.findAllBySalesmanIdAndDelFlag(salesmanId,"0",antPage.getPageRequest());
        int a=shoppingRepository.countAllByDelFlag("0");


         List<Shopping> shoppings=new ArrayList<>();
        for (ShopInfo shopInfo: shopInfos ) {
            List<Shopping> shoppings1=shoppingRepository.findAllByShopIdAndDelFlag(shopInfo.getId(),"0");
            for (Shopping shopping:shoppings1  ) {
                shopping.setShopName(shopInfo.getName());
                Salesman salesman=salesmanRepository.findOne(shopInfo.getSalesmanId());
                shopping.setSalesmanName(salesman.getName());
                shopping.setSalesmanPhone(salesman.getPhone());
                int getNum=0;
                int s=goodsGiftRepository.countShoppingNum(shopping.getId(),"1","0");
                getNum=getNum+s;
                shopping.setGetNum(getNum);
            }
            shoppings.addAll(shoppings1);
        }
        apiResultBean.setData(shoppings,antPage,Long.valueOf(a));
        apiResultBean.setMsg("查询成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }


    public ApiResultBean audit(String salesmanId,String shoppingAplyId){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(salesmanId)|| StringUtil.isEmpty(shoppingAplyId)){
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("业务员id或申请记录为空为空");
            return  apiResultBean;
        }
       ShoppingApply shoppingApply=shoppingApplyRepository.findOne(shoppingAplyId);
        //修改同意状态
        shoppingApply.setIsApply("0");
        shoppingApply.setSalesmanId(salesmanId);
        shoppingApplyRepository.saveAndFlush(shoppingApply);
        MinShoppingUserInfo minUserInfo=minUserInfoRepository.findOne(shoppingApply.getMiniUserId());
      //添加导购信息
        minUserInfo.setMinUserType(MinUserType.SHOPPING);
        minUserInfoRepository.saveAndFlush(minUserInfo);
       Shopping shopping=new Shopping();
       shopping.setIsPerpetual(shoppingApply.getIsPerpetual());
       shopping.setMiniUserId(shoppingApply.getMiniUserId());
       shopping.setSalesmanId(salesmanId);
       shopping.setName(minUserInfo.getNickName());
       shopping.setPhone(minUserInfo.getPhone());
       shopping.setShopId(shoppingApply.getShopId());
        shoppingRepository.saveAndFlush(shopping);
       return  apiResultBean;
    }

    public ApiResultBean queryShoppingApply(String salesmanId, AntPage antPage){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(salesmanId)){
            apiResultBean.setMsg("业务员id不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }
        Page<ShoppingApply> shoppingApplies=shoppingApplyRepository.findAllBySalesmanIdAndDelFlag(salesmanId,"0",antPage.getPageRequest());
        List<ApplyLogVo> applyLogVos=new ArrayList<>();
        if(shoppingApplies.getSize()>0){
            for (ShoppingApply shoppingApply: shoppingApplies ) {
            ApplyLogVo applyLogVo=new ApplyLogVo();
            ShopInfo shopInfo=shopInfoRepository.findOne(shoppingApply.getShopId());
            if(shopInfo!=null){
                applyLogVo.setShopName(shopInfo.getName());
            }
            MinShoppingUserInfo minUserInfo=minUserInfoRepository.findOne(shoppingApply.getMiniUserId());
            if(minUserInfo!=null){
                applyLogVo.setName(minUserInfo.getNickName());
                applyLogVo.setPhone(minUserInfo.getPhone());
                applyLogVo.setImage(minUserInfo.getPhotoUrl());
            }
            applyLogVo.setIsPerpetual(shoppingApply.getIsPerpetual());
            applyLogVo.setShoppingAplyId(shoppingApply.getId());
            applyLogVos.add(applyLogVo);
            }
        }
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("查看成功");
        apiResultBean.setData(applyLogVos,antPage,shoppingApplies.getTotalElements());
        return  apiResultBean;
    }

    public  ApiResultBean queryShop(String salesmanId,AntPage antPage,String field  ){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(salesmanId)){
            apiResultBean.setMsg("参数有误");
            apiResultBean.setCode(ApiResultBean.SUCCESS);
            return  apiResultBean;
        }
        Page<ShopInfo> shopInfos=shopInfoRepository.findAllBySalesmanIdAndDelFlagAndNameContaining(salesmanId,"0",field,antPage.getPageRequest());
        Page<ShopInfo> shopInfos1=shopInfoRepository.findAllBySalesmanIdAndDelFlagAndPhoneContains(salesmanId,"0",field,antPage.getPageRequest());
        List<ShopInfo> shopInfos2=new ArrayList<>();

        if(shopInfos.getSize()>0){
            for (ShopInfo shopInfo: shopInfos ) {
                shopInfos2.add(shopInfo);
            }
        }

        if(shopInfos1.getSize()>0){
            for (ShopInfo shopInfo: shopInfos1 ) {
                shopInfos2.add(shopInfo);
            }
        }

        Set<ShopInfo> ts = new HashSet<ShopInfo>();
        ts.addAll(shopInfos2);

        if(ts.size()>0){
            for (ShopInfo shopInfo: shopInfos  ) {
                List<ShopLibory> shopLibories=shoppingLiboryRepository.findAllByShopIdAndDelFlag(shopInfo.getId(),"0");
                int giftNum=0;
                if(shopLibories.size()>0){
                    for (ShopLibory shopLibory:shopLibories  ) {
                        giftNum=giftNum+shopLibory.getTotalNum();
                    }

                }
                shopInfo.setGiftNum(giftNum);
                int getNum=goodsGiftRepository.countshop(shopInfo.getId(),"1","0");
                shopInfo.setGetNum(getNum);
                int shoppingNum=shoppingRepository.countAllByShopIdAndDelFlag(shopInfo.getId(),"0");
                shopInfo.setShoppingNum(shoppingNum);
            }
        }

        List<ShopInfo> shopInfos3=new ArrayList<ShopInfo>();
        shopInfos3.addAll(ts);


        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setData(shopInfos3,antPage,shopInfos.getTotalElements()+shopInfos1.getTotalElements());
        return  apiResultBean;
    }

    public ApiResultBean salesmanQueryShop(String salesmanId,AntPage antPage){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(salesmanId)){
            apiResultBean.setMsg("参数不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }

        Page<ShopInfo> shopInfos=shopInfoRepository.findAllBySalesmanIdAndDelFlag(salesmanId,"0",antPage.getPageRequest());

        apiResultBean.setData(shopInfos,antPage);
        return  apiResultBean;
    }

    public ApiResultBean goodsGiftDetail(String goodsId,String shopId,AntPage antPage,String salesmanId){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(goodsId)){
            apiResultBean.setMsg("参数不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }


        HashMap<String,Goods> hashMap=new HashMap<>();
        Goods goods=goodsRepository.findAllByIdAndDelFlag(goodsId,"0");
        int a=goodsGiftRepository.countAllBySalesmanIdAndDelFlagAndStateAndGoodsIdAndShopIdContains(salesmanId,"0","1",goodsId,shopId);
        goods.setSendNum(a);
        List<ShoppingGiftChangeLog> logs = shoppingGiftChangeLogRepository.findAllBySalesmanIdAndDelFlagAndGiftChangeAndGooodId(salesmanId, "0", GiftChange.ALLOCATION,goods.getId());
        int s2 = 0;
        if (logs.size() > 0) {
            for (ShoppingGiftChangeLog shoppingGiftChangeLog : logs) {
                s2 = s2 + shoppingGiftChangeLog.getChangeNum();
            }

        }
        //找出业务员所有的收回记录
        List<ShoppingGiftChangeLog> logs1 = shoppingGiftChangeLogRepository.findAllBySalesmanIdAndDelFlagAndGiftChangeAndGooodId(salesmanId, "0", GiftChange.WITHDRAW,goods.getId());
        int s3 = 0;
        if (logs1.size() > 0) {
            for (ShoppingGiftChangeLog shoppingGiftChangeLog : logs1) {
                s3 = s3 + shoppingGiftChangeLog.getChangeNum();
            }

        }
        if(s2>s3){
            goods.setTotalNums(s2-s3);


        }

       hashMap.put("goods",goods);
    Page<ShopInfo> shopInfos=shopInfoRepository.findAllBySalesmanIdAndDelFlagAndIdContains(salesmanId,"0",shopId,antPage.getPageRequest());
        List<ShopDetailsVo> shopDetailsVos=new ArrayList<>();
        if(shopInfos.getSize()>0){
            for (ShopInfo shopInfo:shopInfos   ) {
                ShopDetailsVo shopDetailsVo=new ShopDetailsVo();
                shopDetailsVo.setShopName(shopInfo.getName());
                List<ShoppingGiftChangeLog> log = shoppingGiftChangeLogRepository.findAllBySalesmanIdAndDelFlagAndGiftChangeAndGooodIdAndShopId(salesmanId, "0", GiftChange.ALLOCATION,goods.getId(),shopInfo.getId());
                int l1 = 0;
                if (logs.size() > 0) {
                    for (ShoppingGiftChangeLog shoppingGiftChangeLog : log) {
                        l1 = l1 + shoppingGiftChangeLog.getChangeNum();
                    }

                }
                //找出业务员所有的收回记录
                List<ShoppingGiftChangeLog> log1 = shoppingGiftChangeLogRepository.findAllBySalesmanIdAndDelFlagAndGiftChangeAndGooodIdAndShopId(salesmanId, "0", GiftChange.WITHDRAW,goods.getId(),shopInfo.getId());
                int l2 = 0;
                if (logs1.size() > 0) {
                    for (ShoppingGiftChangeLog shoppingGiftChangeLog : log1) {
                        l2 = l2 + shoppingGiftChangeLog.getChangeNum();
                    }

                }
                if(l1>l2){
                    shopDetailsVo.setTotalNums(l1-l2);

                }
                int s=goodsGiftRepository.countAllBySalesmanIdAndDelFlagAndStateAndGoodsIdAndShopIdContains(salesmanId,"0","1",goodsId,shopInfo.getId());
                shopDetailsVo.setGetNums(s);
                List<String > strings=goodsGiftRepository.findAllDistinctByUShoppingId("1","0",shopInfo.getId(),goods.getId());
                List<ShopDetailVo> shopDetailVos=new ArrayList<>();
                if(strings.size()>0){
                    for (String str:strings ) {
                        ShopDetailVo shopDetailVo=new ShopDetailVo();
                        Shopping shopping=shoppingRepository.findAllByIdAndDelFlag(str,"0");
                        int b=goodsGiftRepository.countAllByShoppingIdAndDelFlagAndStateAndGoodsId(str,"0","1",goods.getId());
                        shopDetailVo.setGetNum(b);
                        shopDetailVo.setIsPerpetual(shopping.getIsPerpetual());
                        shopDetailVo.setShoppingName(shopping.getName());
                        shopDetailVos.add(shopDetailVo);

                    }
                }
                shopDetailsVo.setShopDetailVos(shopDetailVos);

                shopDetailsVos.add(shopDetailsVo);

            }




        }
        apiResultBean.setData(goods);
        apiResultBean.setData(shopDetailsVos,antPage,shopInfos.getTotalElements());
        apiResultBean.setMsg("成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return  apiResultBean;

    }
}
